<template>
	<view class="x-media-placeholder auto-img">
		<!-- 占位 -->
		<view v-show="loading || errorload"
			:style="{ opacity: '0', width: containerScale, height: containerScale }">
		</view>
		<!-- 加载中 -->
		<view v-if="loading" class="flex-center-center auto-img status-placeholder">
			<view class="clear-flex">
				<Loading1></Loading1>
			</view>
		</view>
		<!-- 加载失败 -->
		<view v-else-if="errorload" class="flex-center-center status-placeholder">
			<view class="clear-flex">
				<Error1></Error1>
			</view>
		</view>
		<!-- 图片 -->
		<view v-show="!loading && !errorload" :style="{ width, height }">
			<image :src="src" style="transition: .4s linear opacity;" :class="[showStatus ? 'x-image-show' : 'x-image']"
				:mode="mode" @load="handlerLoad" @error="handlerError" @click="previewAction"></image>
		</view>
	</view>
</template>

<script>
	import Loading1 from './anime/loading-1.vue'
	import Error1 from './anime/error-1.vue'
	export default {
		components: {
			Loading1,
			Error1
		},
		props: {
			src: {
				default: ''
			},
			mode: {
				default: 'scaleToFill'
			},
			preview: {
				default: false
			}
		},
		data() {
			return {
				loading: true,
				errorload: false,
				showStatus: false,

				containerScale: '100%',
				width: '100%',
				height: 'auto'
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.query('.x-media-placeholder').then(data => {
					if (data.width === 0) {
						console.log(data)
					}
					this.containerScale = data.width ? `${ data.width }px` : `100%`
				})
			})
		},
		methods: {
			previewAction() {
				if (!this.loading && !this.errorload && this.preview) {
					this.previewImage([this.src])
				}
			},
			handlerLoad(e) {
				this.loading = false
				this.$nextTick(() => {
					this.height = '100%'
					setTimeout(() => {
						this.$set(this, 'showStatus', true)
					}, 500)
				})
			},
			handlerError(e) {
				this.loading = false
				this.height = '100%'
				this.errorload = true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.x-media-placeholder {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}

	.status-placeholder {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.x-image {
		width: 100%;
		height: 100%;
		opacity: 0;
		transform: scale(0);
		transition: 1s linear all;

		&-show {
			@extend .x-image;
			opacity: 1;
			transform: scale(1);
		}
	}
</style>
